<?php

namespace App\Http\Controllers\CmsApi;

use App\Http\Controllers\BaseController;
use App\Http\Model\Hint;
use App\Http\Model\OutJson;
use App\Http\Model\RoomBackgroundPicture\BackgroundPictureManagement;
use App\Http\Model\RoomBackgroundPicture\BackgroundPictureSpecial;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RoomBackgroundPictureManagementController extends BaseController
{
    /**
     * 表单验证，公共的message
     *
     * @var string[]
     */
    public $commonMessages = [
        'type.required' => '请选择展示位置',
        'type.in' => '展示位置参数错误',
        'is_show.in' => '是否展示参数错误',
        'weight.required' => '请输入展示权重',
        'weight.integer' => '展示权重必须为正整数',
        'resource_url.required' => '请上传资源图',
        'resource_url2.required' => '请上传资源图2',
    ];

    /**
     * 表单验证-公共的验证规则
     *
     * @var string[]
     */
    public $commonRules = [];

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->commonRules = [
            'type' => 'required|in:' . implode(',', array_column(BackgroundPictureManagement::getTypes(), 'id')),
            'is_show' => 'in:' . implode(',', BackgroundPictureManagement::getIsShowStatus()),
            'weight' => 'required|integer',
            'resource_url' => 'required',
            'resource_url2' => 'required',
            'room_uuids' => 'nullable',
            'start_time' => 'required|integer',
            'end_time' => 'required|integer',
        ];
    }

    /**
     * 获取展示位置
     *
     * Created at 2021/11/12 11:49
     * @Author <yuxiang.zhu@asiainnovations.net>
     */
    public function getTypes()
    {
        OutJson::outJsonResult(Hint::SUCCESS, BackgroundPictureManagement::getTypes());
    }

    /**
     * 获取列表
     *
     * Created at 2021/11/12 11:55
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     */
    public function getList(Request $request)
    {
        $page = intval($request->input('page', 1));
        if ($page <= 0) {
            $page = 1;
        }

        $limit = intval($request->input('limit'));
        if ($limit <= 0) {
            $limit = 10;
        }

        $result = ['page' => $page, 'limit' => $limit, 'total' => 0, 'page_total' => 1, 'list' => []];
        $result['total'] = $count = BackgroundPictureManagement::query()->count();
        if ($count) {
            $start = ($page - 1) * $limit;
            if ($count > $limit) {
                $result['page_total'] = intval(ceil($count / $limit));
            }

            $list = BackgroundPictureManagement::query()->limit($limit)->offset($start)->orderByDesc('id')->get()->toArray();
            foreach ($list as &$item) {
                $item['room_uuids'] = BackgroundPictureSpecial::getRoomUuids($item['id']);
            }

            $result['list'] = $list;
        }

        OutJson::outJsonResult(Hint::SUCCESS, $result);
    }

    /**
     * 添加
     *
     * Created at 2021/11/12 12:16
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     */
    public function add(Request $request)
    {
        $params = parent::validateParams($request->all(), $this->commonRules, $this->commonMessages);
        DB::beginTransaction();
        $model = BackgroundPictureManagement::query()->create($params);
        if ($params['type'] == BackgroundPictureManagement::TYPE_OF_SPECIAL_CBD) {
            BackgroundPictureSpecial::resetRoomUuids($model->id, explode(',', $params['room_uuids']));
        }

        DB::commit();

        //删除缓存
        BackgroundPictureManagement::clearPictureCache($params['resource_url']);
        BackgroundPictureManagement::clearPictureCache($params['resource_url2']);

        OutJson::outJsonResult(Hint::SUCCESS);
    }

    /**
     * 编辑
     *
     *
     * Created at 2021/11/12 12:18
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     */
    public function update(Request $request)
    {
        $rules = array_merge(['id' => 'required|exists:room_background_picture_management'], $this->commonRules);
        $messages = array_merge(['id.required' => '缺少id参数', 'id.exists' => '记录不存在'], $this->commonMessages);
        $params = parent::validateParams($request->all(), $rules, $messages);
        DB::beginTransaction();
        $roomUuids = $params['room_uuids'] ?? [];
        if ($roomUuids) {
            unset($params['room_uuids']);
        }

        BackgroundPictureManagement::query()->where('id', $params['id'])->update($params);
        if ($params['type'] == BackgroundPictureManagement::TYPE_OF_SPECIAL_CBD) {
            BackgroundPictureSpecial::resetRoomUuids(intval($params['id']), explode(',', $roomUuids));
        }

        //删除缓存
        BackgroundPictureManagement::clearPictureCache($params['resource_url']);
        BackgroundPictureManagement::clearPictureCache($params['resource_url2']);
        DB::commit();
        OutJson::outJsonResult(Hint::SUCCESS);
    }

    /**
     * 删除
     *
     * Created at 2021/11/12 12:22
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param Request $request
     */
    public function delete(Request $request)
    {
        $rules = ['id' => 'required|exists:room_background_picture_management'];
        $messages = ['id.required' => '缺少id参数', 'id.exists' => '记录不存在'];
        $params = parent::validateParams($request->all(), $rules, $messages);
        DB::beginTransaction();
        $query = BackgroundPictureManagement::query()->where('id', $params['id'])->first();
        BackgroundPictureManagement::query()->where('id', $params['id'])->delete();
        if ($query && $query->type == BackgroundPictureManagement::TYPE_OF_SPECIAL_CBD) {
            BackgroundPictureSpecial::resetRoomUuids(intval($params['id']), []);
        }

        DB::commit();
        OutJson::outJsonResult(Hint::SUCCESS);
    }
}